// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Text;
using Antlr4.Runtime.Misc;
using Templating.Grammar.Antlr;
using static Templating.Grammar.Antlr.TemplatingParser;

namespace SnapObjects.Data
{
    internal partial class DataTemplateConverter
        : TemplatingParserBaseVisitor<StringBuilder>
        , ITemplatingParserVisitor<StringBuilder>
    {
        public override StringBuilder VisitExpr([NotNull] ExprContext context)
        {
            var text = context.TOKEN_EXPR().GetText();

            var expr = text.Trim();

            var result = _exprRegex.Match(expr);

            if (result.Success)
            {
                expr = _dataFormat.Format(result.Groups[1].Value)?.ToString();
            }
            
            return _builder.Append(expr);
        }

        public override StringBuilder VisitParentPart([NotNull] ParentPartContext context)
        {
            _builder.Append(context.TOKEN_OP_LBRACKET().GetText());

            var expressions = context.part();

            Array.ForEach(expressions, x => this.Visit(x));

            return _builder.Append(context.TOKEN_OP_RBRACE().GetText());
        }
    }
}
